package com.ruoyi.business.utils;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.exception.ServiceException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 英文名工具类
 *
 * @author Tellsea
 * @date 2024-04-16
 */
public class NameUtils {

    /**
     * 中文转拼音
     *
     * @param chinese 中文
     * @return
     */
    public static String toPinyin(String chinese) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        char[] input = chinese.trim().toCharArray();
        StringBuilder output = new StringBuilder();

        try {
            for (char c : input) {
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    output.append(pinyinArray[0]);
                } else {
                    output.append(c);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
            throw new ServiceException("拼音解析异常：" + e.getMessage());
        }
        return output.toString();
    }

    /**
     * 中文名字转英文名字
     * 汤海鸿 = H H Tang
     *
     * @param chinese
     * @return
     */
    public static String toEnglishPinyin(String chinese) {
        char[] input = chinese.trim().toCharArray();
        if (input.length == 0) {
            return null;
        }
        if (input.length == 1) {
            return toPinyin(chinese);
        }
        StringBuilder englishName = new StringBuilder();
        for (int i = 1; i < input.length; i++) {
            String pinyin = toPinyin(String.valueOf(input[i]));
            if (StrUtil.isNotEmpty(pinyin.trim())) {
                char name = pinyin.trim().toCharArray()[0];
                englishName.append(String.valueOf(name).toUpperCase()).append(" ");
            }

        }
        englishName.append(firstLetterToUpperCase(toPinyin(String.valueOf(input[0]))));
        return englishName.toString();
    }

    public static String firstLetterToUpperCase(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        char firstChar = Character.toUpperCase(str.charAt(0));
        return firstChar + str.substring(1);
    }

    public static void main(String[] args) {
        String name = "汤紫星";
        System.out.println(toEnglishPinyin(name));
        System.out.println(toEnglishPinyin("1"));
    }
}
